/*
 * 闯关测试模板
 */

import * as React from 'react';
import { connect } from 'react-redux';

import { Table, Card, Button, message } from 'antd';
import EditForm from './EditForm';
import CustomModal from 'components/common/CustomModal';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/test';

import { fetchTestTplList, createTestTpl, updateTestTpl } from 'actions/test';

interface TplProps {
  dispatch: (action: any) => any;
  loadingGroup: any;
  tplList: object[];
  tplTotal: number;
}
interface TplState {
  editTpl: any;
  modalVisible: boolean;
}

class TplList extends React.Component<TplProps, TplState> {
  pageInit: number;
  pageSizeInit: number;
  filters: any;

  static defaultProps: TplProps = {
    dispatch: () => {},
    loadingGroup: {},
    tplList: [],
    tplTotal: 0,
  };
  constructor(props: TplProps) {
    super(props);
    this.state = {
      modalVisible: false,
      editTpl: null,
    };

    this.pageInit = 1;
    this.pageSizeInit = 10;
    this.filters = {
      page: this.pageInit,
      pageSize: this.pageSizeInit,
    };
  }

  componentDidMount() {
    this.handleFetchTplList();
  }

  /**
   * 查询测试模板
   */
  handleFetchTplList = (params: any = {}, isSearch: boolean = false) => {
    this.filters = { ...this.filters, ...params };
    if (isSearch) {
      this.filters.page = this.pageInit;
    }

    this.props.dispatch(fetchTestTplList(this.filters));
  };

  showModal = (editTpl: any = 0) => {
    this.setState({
      modalVisible: true,
      editTpl,
    });
  };

  hideModal = () => {
    this.setState({
      modalVisible: false,
    });
  };

  /**
   * 创建或更新学期
   */
  handleEditorSubmit = (data: Record<string, any>) => {
    const { loadingGroup } = this.props;
    const { editTpl } = this.state;

    const loadingKey = editTpl ? ACTIONS.UPDATE_TPL : ACTIONS.CREATE_TPL;

    if (isLoading(loadingGroup, loadingKey)) return;

    const action = editTpl ? updateTestTpl(editTpl.id, data) : createTestTpl(data);

    this.props.dispatch(action).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        let msg = editTpl ? '修改成功' : '创建成功';
        message.success(msg);

        this.handleFetchTplList();
        this.hideModal();
      }
    });
  };

  // 分页回调
  onPageChange = (current: number) => {
    this.handleFetchTplList({ current });
  };

  render() {
    let { loadingGroup, tplList, tplTotal } = this.props;
    const { modalVisible, editTpl } = this.state;

    const loadingKey = editTpl ? ACTIONS.UPDATE_TPL : ACTIONS.CREATE_TPL;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total: Number) => `总共${total}条`,
      current: this.filters.page,
      pageSize: this.filters.pageSize,
      total: tplTotal,
      onChange: this.onPageChange,
    };

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
      },
      {
        title: '描述',
        dataIndex: 'description',
      },
      {
        title: '操作',
        render: (text: any, record: any) => (
          <React.Fragment>
            <Button
              icon="edit"
              onClick={() => {
                this.showModal(record);
              }}>
              编辑
            </Button>
          </React.Fragment>
        ),
      },
    ];

    const modalProps = {
      title: editTpl ? '编辑模板' : '新增模板',
      visible: modalVisible,
      onCancel: this.hideModal,
      footer: false,
    };

    return (
      <div>
        <Card style={{ marginTop: 24 }}>
          <Table
            loading={isLoading(loadingGroup, ACTIONS.FETCH_TPL_LIST)}
            size="small"
            rowKey={record => {
              return String(record.id);
            }}
            bordered={false}
            pagination={paginationProps}
            dataSource={tplList}
            columns={columns}
          />
        </Card>
        <CustomModal {...modalProps}>
          <EditForm
            loading={isLoading(loadingGroup, loadingKey)}
            tpl={editTpl}
            onSubmit={this.handleEditorSubmit}
          />
        </CustomModal>
      </div>
    );
  }
}

function mapStateToProps(state: any) {
  const { loadingGroup } = state;
  const { tplList, tplTotal } = state.test;

  return {
    loadingGroup,
    tplList,
    tplTotal,
  };
}

export default connect(mapStateToProps)(TplList);
